<template>
  <div class="analytics-page">
    <NavBar title="数据分析" :show-home-button="true">
      <template #right>
        <van-icon name="setting-o" size="20" @click="showSettings = true" />
      </template>
    </NavBar>
    
    <div class="page-container">
      <!-- 时间选择器 -->
      <div class="time-selector card">
        <van-tabs v-model:active="activeTimeTab" @change="handleTimeChange">
          <van-tab title="今日" />
          <van-tab title="近7天" />
          <van-tab title="近30天" />
          <van-tab title="自定义" />
        </van-tabs>
        <div v-if="activeTimeTab === 3" class="custom-time">
          <van-field
            v-model="customStartDate"
            readonly
            label="开始日期"
            placeholder="选择开始日期"
            @click="showStartPicker = true"
          />
          <van-field
            v-model="customEndDate"
            readonly
            label="结束日期"
            placeholder="选择结束日期"
            @click="showEndPicker = true"
          />
        </div>
      </div>

      <!-- 核心指标卡片 -->
      <div class="metrics-section">
        <van-grid :column-num="2" :gutter="10" :border="false">
          <van-grid-item
            v-for="metric in metricsData"
            :key="metric.key"
            class="metric-card"
          >
            <div class="metric-content">
              <div class="metric-header">
                <van-icon :name="metric.icon" :color="metric.color" size="20" />
                <span class="metric-title">{{ metric.title }}</span>
              </div>
              <div class="metric-value">{{ metric.value }}</div>
              <div class="metric-change" :class="metric.trend">
                <van-icon :name="metric.trend === 'up' ? 'arrow-up' : 'arrow-down'" size="10" />
                {{ metric.change }}
                <span class="metric-period">vs {{ getTimeRangeText() }}</span>
              </div>
            </div>
          </van-grid-item>
        </van-grid>
      </div>

      <!-- 趋势分析 -->
      <div class="trend-section">
        <BaseChart
          title="访问量趋势"
          type="line"
          :data="visitTrendData"
          height="250px"
        />
      </div>

      <!-- 用户行为分析 -->
      <div class="behavior-section">
        <BaseChart
          title="用户行为分布"
          type="pie"
          :data="behaviorData"
          height="280px"
        />
      </div>

      <!-- 地域分析 -->
      <div class="region-section card">
        <h3 class="section-title">地域分析</h3>
        <div class="region-list">
          <div
            v-for="region in regionData"
            :key="region.name"
            class="region-item"
          >
            <div class="region-info">
              <span class="region-name">{{ region.name }}</span>
              <span class="region-value">{{ region.value }}</span>
            </div>
            <div class="region-bar">
              <div
                class="region-progress"
                :style="{ width: `${(region.value / maxRegionValue) * 100}%` }"
              ></div>
            </div>
            <div class="region-percent">{{ region.percent }}%</div>
          </div>
        </div>
      </div>

      <!-- 转化漏斗 -->
      <div class="funnel-section card">
        <h3 class="section-title">转化漏斗</h3>
        <div class="funnel-chart">
          <div
            v-for="(step, index) in funnelData"
            :key="step.name"
            class="funnel-step"
            :class="{ 'active': index === activeFunnelStep }"
            @click="activeFunnelStep = index"
          >
            <div class="step-bar" :style="{ width: `${step.percent}%` }">
              <div class="step-content">
                <span class="step-name">{{ step.name }}</span>
                <span class="step-value">{{ step.value }}</span>
              </div>
            </div>
            <div class="step-percent">{{ step.percent }}%</div>
          </div>
        </div>
      </div>

      <!-- 实时数据 -->
      <div class="realtime-section card">
        <h3 class="section-title">
          实时数据
          <van-tag type="success" size="small">Live</van-tag>
        </h3>
        <div class="realtime-stats">
          <div class="realtime-item">
            <span class="realtime-label">在线用户</span>
            <span class="realtime-value">{{ realtimeData.onlineUsers }}</span>
          </div>
          <div class="realtime-item">
            <span class="realtime-label">今日PV</span>
            <span class="realtime-value">{{ realtimeData.todayPV }}</span>
          </div>
          <div class="realtime-item">
            <span class="realtime-label">今日UV</span>
            <span class="realtime-value">{{ realtimeData.todayUV }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showStartPicker" position="bottom">
      <van-date-picker
        v-model="tempStartDate"
        @confirm="onStartDateConfirm"
        @cancel="showStartPicker = false"
      />
    </van-popup>

    <van-popup v-model:show="showEndPicker" position="bottom">
      <van-date-picker
        v-model="tempEndDate"
        @confirm="onEndDateConfirm"
        @cancel="showEndPicker = false"
      />
    </van-popup>

    <!-- 设置弹窗 -->
    <van-popup
      v-model:show="showSettings"
      position="bottom"
      :style="{ height: '50%' }"
      round
    >
      <div class="popup-header">
        <h3>分析设置</h3>
        <van-icon name="cross" @click="showSettings = false" />
      </div>
      <div class="popup-content">
        <van-cell-group>
          <van-cell title="自动刷新" is-link>
            <template #value>
              <van-switch v-model="autoRefresh" @change="handleAutoRefreshChange" />
            </template>
          </van-cell>
          <van-cell title="刷新间隔" is-link @click="showIntervalPicker = true">
            <template #value>{{ refreshInterval }}秒</template>
          </van-cell>
          <van-cell title="数据导出" is-link @click="exportAnalyticsData">
            <template #value>
              <van-icon name="download" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>
    </van-popup>

    <TabBar />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { showToast } from 'vant'
import dayjs from 'dayjs'
import NavBar from '@/components/NavBar.vue'
import TabBar from '@/components/TabBar.vue'
import BaseChart from '@/components/BaseChart.vue'

// 响应式数据
const activeTimeTab = ref(0)
const activeFunnelStep = ref(0)
const showStartPicker = ref(false)
const showEndPicker = ref(false)
const showSettings = ref(false)
const showIntervalPicker = ref(false)
const autoRefresh = ref(true)
const refreshInterval = ref(30)

// 日期选择
const customStartDate = ref('')
const customEndDate = ref('')
const tempStartDate = ref<string[]>([])
const tempEndDate = ref<string[]>([])

// 自动刷新定时器
let refreshTimer: number | null = null

// 核心指标数据
const metricsData = ref([
  {
    key: 'pv',
    title: '页面浏览量',
    value: '128,543',
    icon: 'eye-o',
    color: '#1890ff',
    change: '+12.3%',
    trend: 'up'
  },
  {
    key: 'uv',
    title: '独立访客',
    value: '23,456',
    icon: 'user-o',
    color: '#52c41a',
    change: '+8.7%',
    trend: 'up'
  },
  {
    key: 'bounce',
    title: '跳出率',
    value: '32.1%',
    icon: 'warning-o',
    color: '#faad14',
    change: '-2.1%',
    trend: 'down'
  },
  {
    key: 'session',
    title: '平均会话时长',
    value: '3m 42s',
    icon: 'clock-o',
    color: '#f5222d',
    change: '+15.2%',
    trend: 'up'
  }
])

// 访问趋势数据
const visitTrendData = ref([
  { name: '00:00', value: 120 },
  { name: '04:00', value: 80 },
  { name: '08:00', value: 200 },
  { name: '12:00', value: 350 },
  { name: '16:00', value: 280 },
  { name: '20:00', value: 180 }
])

// 用户行为数据
const behaviorData = ref([
  { name: '浏览商品', value: 3500 },
  { name: '加入购物车', value: 1200 },
  { name: '发起支付', value: 800 },
  { name: '完成购买', value: 600 },
  { name: '评价商品', value: 200 }
])

// 地域数据
const regionData = ref([
  { name: '北京', value: 8963, percent: 28.5 },
  { name: '上海', value: 6543, percent: 20.8 },
  { name: '广州', value: 5432, percent: 17.3 },
  { name: '深圳', value: 4321, percent: 13.7 },
  { name: '杭州', value: 3210, percent: 10.2 },
  { name: '其他', value: 2987, percent: 9.5 }
])

// 转化漏斗数据
const funnelData = ref([
  { name: '访问首页', value: 10000, percent: 100 },
  { name: '浏览商品', value: 8500, percent: 85 },
  { name: '加入购物车', value: 3200, percent: 32 },
  { name: '发起支付', value: 1800, percent: 18 },
  { name: '完成支付', value: 1200, percent: 12 }
])

// 实时数据
const realtimeData = ref({
  onlineUsers: 1247,
  todayPV: 89563,
  todayUV: 12845
})

// 计算最大地域值
const maxRegionValue = computed(() => {
  return Math.max(...regionData.value.map(item => item.value))
})

// 获取时间范围文本
const getTimeRangeText = () => {
  switch (activeTimeTab.value) {
    case 0:
      return '昨日'
    case 1:
      return '上周'
    case 2:
      return '上月'
    case 3:
      return '前期'
    default:
      return '前期'
  }
}

// 处理时间选择变化
const handleTimeChange = (index: number) => {
  activeTimeTab.value = index
  loadAnalyticsData()
}

// 确认开始日期
const onStartDateConfirm = (values: string[]) => {
  customStartDate.value = values.join('-')
  showStartPicker.value = false
  loadAnalyticsData()
}

// 确认结束日期
const onEndDateConfirm = (values: string[]) => {
  customEndDate.value = values.join('-')
  showEndPicker.value = false
  loadAnalyticsData()
}

// 处理自动刷新变化
const handleAutoRefreshChange = (value: boolean) => {
  if (value) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
}

// 开始自动刷新
const startAutoRefresh = () => {
  stopAutoRefresh()
  refreshTimer = setInterval(() => {
    loadAnalyticsData()
    // 更新实时数据
    realtimeData.value.onlineUsers = Math.floor(Math.random() * 2000) + 1000
    realtimeData.value.todayPV += Math.floor(Math.random() * 100) + 50
    realtimeData.value.todayUV += Math.floor(Math.random() * 20) + 10
  }, refreshInterval.value * 1000)
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 导出分析数据
const exportAnalyticsData = () => {
  showToast('导出功能开发中...')
  showSettings.value = false
}

// 加载分析数据
const loadAnalyticsData = async () => {
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 这里可以根据时间范围加载不同的数据
    console.log('加载分析数据', {
      timeTab: activeTimeTab.value,
      startDate: customStartDate.value,
      endDate: customEndDate.value
    })
    
    showToast('数据已更新')
  } catch (error) {
    console.error('加载分析数据失败:', error)
    showToast('加载数据失败')
  }
}

onMounted(() => {
  loadAnalyticsData()
  if (autoRefresh.value) {
    startAutoRefresh()
  }
})

onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style scoped>
.analytics-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
}

.time-selector {
  margin-bottom: 16px;
}

.custom-time {
  padding: 16px 0;
}

.metrics-section {
  margin-bottom: 16px;
}

.metric-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.metric-content {
  text-align: left;
}

.metric-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.metric-title {
  font-size: 12px;
  color: #666;
}

.metric-value {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.metric-change {
  font-size: 11px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.metric-change.up {
  color: #52c41a;
}

.metric-change.down {
  color: #f5222d;
}

.metric-period {
  color: #999;
  margin-left: 4px;
}

.trend-section,
.behavior-section {
  margin-bottom: 16px;
}

.region-section,
.funnel-section,
.realtime-section {
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.region-list {
  space-y: 12px;
}

.region-item {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.region-info {
  min-width: 80px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.region-name {
  font-size: 14px;
  color: #333;
}

.region-value {
  font-size: 12px;
  color: #666;
}

.region-bar {
  flex: 1;
  height: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.region-progress {
  height: 100%;
  background: linear-gradient(90deg, #1890ff, #52c41a);
  transition: width 0.3s;
}

.region-percent {
  min-width: 40px;
  text-align: right;
  font-size: 12px;
  color: #666;
}

.funnel-chart {
  space-y: 8px;
}

.funnel-step {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  margin-bottom: 8px;
}

.funnel-step.active .step-bar {
  background: linear-gradient(90deg, #1890ff, #52c41a);
}

.step-bar {
  flex: 1;
  height: 40px;
  background: linear-gradient(90deg, #e6f7ff, #f0f2f5);
  border-radius: 20px;
  display: flex;
  align-items: center;
  padding: 0 16px;
  transition: all 0.3s;
}

.step-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  color: #333;
}

.step-name {
  font-size: 14px;
  font-weight: 500;
}

.step-value {
  font-size: 12px;
  font-weight: 600;
}

.step-percent {
  min-width: 50px;
  text-align: right;
  font-size: 12px;
  color: #666;
}

.realtime-stats {
  display: flex;
  justify-content: space-around;
}

.realtime-item {
  text-align: center;
}

.realtime-label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.realtime-value {
  display: block;
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebedf0;
}

.popup-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.popup-content {
  padding: 20px;
}

:deep(.van-grid-item__content) {
  padding: 0;
  background: transparent;
}

:deep(.van-tabs__nav) {
  background: transparent;
}

:deep(.van-tab) {
  font-size: 14px;
}
</style>